package com.pickgliss.utils
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.geom.Point;

	public class PNGHitAreaFactory
	{
		private static var points1:Vector.<Point>;
		private static var points2:Vector.<Point>;
		
		private static var coord:Vector.<Number>;
		private static var commands:Vector.<int>;
		
		public function PNGHitAreaFactory()
		{
		}
		
		public static function drawHitArea(bm:Bitmap):Sprite
		{
			getPointAroundImage(bm);
			
			var sp:Sprite = new Sprite();
			sp.graphics.beginFill(0xff0000);
			sp.graphics.drawPath(commands,coord);
			sp.graphics.endFill();
			sp.x = bm.x;
			sp.y = bm.y;
			commands.length = coord.length = 0;
			return sp;
		}
		
		public static function getPointAroundImage(bm:Bitmap, $x:int=0, $y:int=0):Array
		{
			points1 = new Vector.<Point>();
			points2 = new Vector.<Point>();
			commands = new Vector.<int>();
			coord = new Vector.<Number>();
			var w:int = bm.width;
			var h:int = bm.height;
			var bx:int=$x;
			var by:int=$y;
			var i:int;
			var j:int;
			var k:int;
			for(i=1; i<=w; i++)
			{
				for(j = 1; j<=h; j++)
				{
					var alphaValue:uint = bm.bitmapData.getPixel32(i,j) >> 24 & 0xFF;
					if(alphaValue!=0x00000000)
					{
						points1.push(new Point(i+bx,j+by));
						break;
					}
				}
				for(k = h;k>0;k--)
				{
					var alphaValue1:uint = bm.bitmapData.getPixel32(i,k) >> 24 & 0xFF;
					if(alphaValue1!=0x00000000 && i!=k)
					{
						points2.unshift(new Point(i+bx,k+by));
						break;
					}
				}
			}
			
			for each(var p1:Point in points1)
			{
				coord.push(p1.x);
				coord.push(p1.y);
			}
			for each(var p2:Point in points2)
			{
				coord.push(p2.x);
				coord.push(p2.y);
			}
			var len:uint = points1.length + points2.length;
			commands.push(1);
			for(var l:int = 1;l<len;l++)
			{
				commands.push(2);
			}
			
			points1.length = points2.length = 0;
			return [commands,coord];
		}
	}
}